package com.linkage.seapeak.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.RegistLogin.AccountLoginActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.bean.LoginInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.register.BindAccountActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.QQAuthData;
import com.linkage.seapeak.pojo.WxAuthData;
import com.linkage.seapeak.utils.FileUtils;
import com.linkage.seapeak.utils.HawkKey;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ThridAuthActivity extends BaseWhiteActivity {

    TextView bindQQ, bindWX;
    LoginInfo detail;
    private ShapeLoadingDialog shapeLoadingDialog;
    boolean hasQQ = false, hasWX = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        setContentView(R.layout.activity_thrid_auth, "绑定第三方账号");
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadUI();
    }

    private void loadUI() {
        bindQQ.setText(hasQQ ? "解除" : "绑定");
        bindWX.setText(hasWX ? "解除" : "绑定");
        bindQQ.setTextColor(hasQQ ? 0xff888888 : getResources().getColor(R.color.colorPrimary));
        bindWX.setTextColor(hasWX ? 0xff888888 : getResources().getColor(R.color.colorPrimary));
    }

    private void init() {
        bindQQ = findViewById(R.id.bind_qq);
        bindWX = findViewById(R.id.bind_wx);
//        detail = Hawk.get(HawkKey.LOGINDETIAL, null);
        detail = BankruptcyApp.loginInfo;

        if (detail != null) {
            hasQQ = detail.getQq() != null;
            hasWX = detail.getWx() != null;
        }

        bindQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasQQ) {

//                    authUnbind(true);
                    noticeDialog = new PublicNoticeDialog(ThridAuthActivity.this, onClickListener,
                            1, "提示", "确定解除绑定吗？",
                            "取消", "确定");
                    noticeDialog.show();
                    qqflag  = true;
                } else
                    authLogin(QQ.NAME);
            }
        });
        bindWX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasWX) {
//                    authUnbind(false);
                    noticeDialog = new PublicNoticeDialog(ThridAuthActivity.this, onClickListener,
                            1, "提示", "确定解除绑定吗？",
                            "取消", "确定");
                    noticeDialog.show();
                    qqflag = false;
                } else
                    authLogin(Wechat.NAME);
            }
        });
    }

    Boolean qqflag = true;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.ll_close:
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_chancel_notice:
//                   Boolean flag =  noticelxDialog.cb_agree.isChecked();
                    noticeDialog.dismiss();

                    break;

                case R.id.btn_save_notice:
                    authUnbind(qqflag);
                    noticeDialog.dismiss();
                    break;

            }
        }
    };


    private PublicNoticeDialog noticeDialog;
    /**
     * 授权登录
     * @param name
     */
    public void authLogin(final String name) {
        final Platform authPlatform = ShareSDK.getPlatform(name);
        ShareSDK.setActivity(this);//抖音登录适配安卓9.0
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        authPlatform.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                arg2.printStackTrace();
                showToast("授权失败！");
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> hashMap) {
                //输出所有授权信息
               final String authData = arg0.getDb().exportData();//取到所有数据
                Log.e("zhong", "授权 onComplete: " + authData);
                if (name.equals(QQ.NAME)) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                    QQAuthData data = new Gson().fromJson(authData, QQAuthData.class);
                    qqLogin(data);
                        }
                        });
                } else {
                    /**
                     *
                     * wx
                     */
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Log.e("========", "wx1");
                    WxAuthData data = new Gson().fromJson(authData, WxAuthData.class);
                    wxLogin(data);
                        }

                    });
                }
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                showToast("取消授权！",ToastUtil.TOAST_TYPE.NOSHOW);
            }
        });
        //authorize与showUser单独调用一个即可
        authPlatform.authorize();//要功能不要数据，在监听oncomplete中不会返回用户数据
    }

    /**
     * QQ 登录
     * @param data
     */
    public void qqLogin(final QQAuthData data) {
        OkHttpClient okHttpClient = new OkHttpClient();
        String appInfoId = SPUtils.getInstance(Consts.SPNAME).getString("appInfoId", "");
        RequestBody requestBody = getTokenRequest()
                .add("openid", data.getUserID())
                .add("nickname", data.getNickname())
                .add("figureurl_qq", data.getIcon())
                .add("unionid", data.getUnionid())
                .add("gender", data.getGender().equals("0") ? "男" : "女")
                .add("pay_token", data.getPay_token())
                .add("secret", data.getSecret())
                .add("userID", data.getUserID())
                .add("expiresTime", data.getExpiresTime() + "")
                .add("token", data.getToken())
                .add("expiresIn", data.getExpiresIn() + "")
                .add("pfkey", data.getPfkey())
                .add("pf", data.getPf())
                .add("secretType", data.getSecretType())
                .add("iconQzone", data.getIconQzone())
                .add("figureurl_qq", data.getIcon())
                .add("icon", data.getIcon())
                .add("appInfoId",appInfoId)
                .build();

        Request request = new Request.Builder()
                .url(Consts.WEBURL_QQ_LOGIN)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                hideProgress();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            hideProgress();
                            JSONObject object = new JSONObject(str);
                            Log.i(TAG, "绑定的账号信息 onResponse: " + str);
                            JSONObject info = object.getJSONObject("data");
                            if (info != null){
                                if (info.has("bind") && info.optInt("bind") == 0) {
                                    Log.i(TAG, "run: 已绑定QQ");
//                                    detail = new Gson().fromJson(info.getString("userInfo"), LoginInfo.class);
//                                    Hawk.put(HawkKey.USERTOKEN, info.getString("userToken"));
//                                    Hawk.put(HawkKey.LOGINDETIAL, detail);
//                                    BankruptcyApp.userToken = info.getString("userToken");
//                                    BankruptcyApp.loginInfo = detail;
//                                    hasQQ = true;
//                                    bindQQ.setText(hasQQ ? "解除" : "绑定");ToastUtil

                                    ToastUtil.getInstance(ThridAuthActivity.this).showShortToast("此QQ账号已绑定其他用户");
//                                    ToastUtil.getInstance(ThridAuthActivity.this).showToast("此QQ账号已绑定其他用户");
                                    onResume();
                                } else {
//                                    Log.i(TAG, "run: 未绑定QQ");
//                                    Intent intent = new Intent(ThridAuthActivity.this, BindAccountActivity.class);
//                                    intent.putExtra("data", data);
//                                    startActivity(intent);
//                                    finish();
                                    authbind(true,data.getUserID());
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }


    /**
     * 解绑账号
     */
    public void authUnbind(final boolean isQQ) {
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = getTokenRequest()
                .add("userToken", BankruptcyApp.userToken)
                .add("userId",BankruptcyApp.loginInfo.getId())
                .add("type", (isQQ ? 1 : 2) + "")
                .build();

        Request request = new Request.Builder()
                .url(Consts.WEBURL_UNBIND_AUTH)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            hideProgress();
                            JSONObject object = new JSONObject(str);
                            Log.i(TAG, "解绑账号 onResponse: " + str);
                            if (object.has("code") && object.getInt("code") == 0){
//                                detail = new Gson().fromJson(object.getString("data"), LoginInfo.class);



                                if(isQQ) {
                                    hasQQ = false;
//                                    detail.setQq(null);
                                    bindQQ.setText(hasQQ ? "解除" : "绑定");
                                }else{
                                    hasWX = false;
//                                    detail.setWx(null);
                                    bindWX.setText(hasWX ? "解除" : "绑定");
                                }
//                                BankruptcyApp.loginInfo = detail;
//                                SPUtils.getInstance(Consts.SPNAME).put("userInfo",object.getString("data"));
                                showToast("操作成功");
                                onResume();
                            }else{
                                showToast("失败："+object.optString("msg"));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    /**
     * wx 登录
     *
     * @param data
     */
    public void wxLogin(final WxAuthData data) {
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        String appInfoId = SPUtils.getInstance(Consts.SPNAME).getString("appInfoId", "");
        RequestBody requestBody = getTokenRequest()
                .add("wxid",data.getOpenid())
                .add("openid", data.getOpenid())
                .add("nickname", data.getNickname())
                .add("unionid", data.getUnionid())
                .add("gender", data.getGender().equals("0") ? "男" : "女")
                .add("userID", data.getUserID())
                .add("expiresTime", data.getExpiresTime() + "")
                .add("token", data.getToken())
                .add("expiresIn", data.getExpiresIn() + "")
                .add("headimgurl", data.getIcon())
                .add("icon",data.getIcon())
                .add("appInfoId",appInfoId)
                .build();

        Request request = new Request.Builder()
                .url(Consts.WEBURL_WX_LOGIN)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            shapeLoadingDialog.dismiss();
                            JSONObject object = new JSONObject(str);
                            Log.i(TAG, "绑定的账号信息 onResponse: " + str);
                            if(object.optInt("code") == 0) {
                                JSONObject info = object.getJSONObject("data");

                                if (info != null) {
                                    if (info.has("bind") && info.optInt("bind") == 0) {
                                        Log.i(TAG, "run: 已绑定WX");
                                        LoginInfo userInfo = new Gson().fromJson(info.getString("userInfo"), LoginInfo.class);
//                                    Hawk.put(HawkKey.USERTOKEN, info.getString("userToken"));
//                                    Hawk.put(HawkKey.LOGINDETIAL, userInfo);
//                                        BankruptcyApp.userToken = info.getString("userToken");

//                                        BankruptcyApp.loginInfo = userInfo;
//                                        SPUtils.getInstance(Consts.SPNAME).put("userInfo", object.getString("data"));
//                                        SPUtils.getInstance(Consts.SPNAME).put("userToken", info.getString("userToken"));
//                                        SPUtils.getInstance(Consts.SPNAME).put("userId", userInfo.getId());
                                        ToastUtil.getInstance(ThridAuthActivity.this).showShortToast("此微信账号已绑定其他用户");
//                                        finish();
                                    } else {
                                        Log.i(TAG, "run: 未绑定WX");
//                                        Intent intent = new Intent(ThridAuthActivity.this, BindAccountActivity.class);
//                                        intent.putExtra("data", data);
//                                        startActivity(intent);
//                                        finish();
                                        authbind(false,data.getOpenid());
                                    }
                                }
                            }else{
                                showToast("失败：" + object.optString("msg"));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }


    /**
     * 绑定账号
     */
    public void authbind(final boolean isQQ,String openid) {
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = getTokenRequest()
                .add("userToken", BankruptcyApp.userToken)
                .add("openid", openid)
                .add("type", (isQQ ? 1 : 2) + "")
                .build();

        Request request = new Request.Builder()
                .url(Consts.WEBURL_BIND_USER)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                final String str = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            hideProgress();
                            JSONObject object = new JSONObject(str);
                            Log.i(TAG, "解绑账号 onResponse: " + str);
                            if (object.has("code") && object.getInt("code") == 0){
//                                detail = new Gson().fromJson(object.getString("data"), LoginInfo.class);
                                if(isQQ) {
                                    hasQQ = true;
//                                    detail.setQq("1");
                                    bindQQ.setText(hasQQ ? "解除" : "绑定");
                                }else{
                                    hasWX = true;
//                                    detail.setWx("1");
                                    bindWX.setText(hasWX ? "解除" : "绑定");
                                }

//                                BankruptcyApp.loginInfo = detail;
                                SPUtils.getInstance(Consts.SPNAME).put("userInfo",object.getString("data"));


                                showToast("操作成功");
                                onResume();
                            }else{
                                showToast("失败："+object.optString("msg"));
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }

}
